package org.wx.io.nio.chart;

import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * @description: NIO 聊天室 客户端
 * @author: wangxun
 * @createDate: 2021/2/5
 * @version: 1.0
 */
@Slf4j
public class NIOChartClient {
    public static void main(String[] args)  {
        try {
            SocketChannel socketChannel = SocketChannel.open();
            socketChannel.configureBlocking(false);


            //连接服务器
            if (!socketChannel.connect(new InetSocketAddress("127.0.0.1", 9999))) {

                while (!socketChannel.finishConnect()) {
                    log.info("正在连接服务器..");
                    Thread.sleep(2000);
                }

            }
            Selector selector = Selector.open();
            socketChannel.register(selector, SelectionKey.OP_READ,ByteBuffer.allocate(4096));

            // 新建一个线程去读取数据
            new Thread(()->{
                while (true){
                    try {
                        if(selector.select(500)>0){
                            Set<SelectionKey> selectionKeys = selector.selectedKeys();
                            Iterator<SelectionKey> iterator = selectionKeys.iterator();
                            while (iterator.hasNext()){
                                SelectionKey key = iterator.next();
                                iterator.remove();
                                SocketChannel channel = (SocketChannel) key.channel();
                                ByteBuffer byteBuffer = (ByteBuffer) key.attachment();
                                // 初始化
                                byteBuffer.clear();
                                try {
                                    channel.read(byteBuffer);
                                    byte[] temp = new byte[4096];
                                    byteBuffer.flip();
                                    byteBuffer.get(temp,0,byteBuffer.limit());
                                    System.out.println(new String(temp));
                                } catch (IOException e) {
                                    log.error("服务器掉线...");
                                    System.exit(0);
                                }

                            }
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }).start();


            // 主线程开启输入
            InputStream in = System.in;
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));

            while (true){
                String dataLine = reader.readLine();
                // readLine 读取到换行符才去停止阻塞, 服务端readLine也只有读到换行符才会进行接收

                if (dataLine != null) {

                    byte[] bytes = dataLine.getBytes();
                    socketChannel.write(ByteBuffer.wrap(bytes));
                }
            }
        } catch (IOException e) {
            log.error("连接不上服务器...");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
